package org.bees.cms.web.util.velocity.element;

import net.sf.json.JSONObject;

import org.bees.cms.web.util.velocity.Configuration;
import org.bees.cms.web.util.velocity.renderer.Renderer;

public class Column extends AbstractElement {
	private static final long serialVersionUID = -961834629733913504L;

	private String name;
	private String property;
	private String width = "10%";
	private Renderer renderer;

	@Override
	public void from(JSONObject t) throws Exception {
		super.from(t);
		// 得到默认渲染器的 key
		String _default = Configuration.getProperty("renderer.default");

		// 获取json中有用的属性 如果取不到 一直采用默认的即原来的
		name = t.containsKey("name") ? t.getString("name") : name;
		property = t.containsKey("property") ? t.getString("property") : property;
		width = t.containsKey("width") ? t.getString("width") : width;

		// 得到渲染器 如果没有指定 那么采用缺省的
		JSONObject param = null;
		String key = null;
		if (t.containsKey("renderer")) {
			param = t.getJSONObject("renderer");
			key = param.containsKey("type") ? param.getString("type") : _default;
			// 如果是个空的json 那么重新实例化 不然没法accumulate
			if (param.isEmpty()) {
				param = new JSONObject();
			}
		} else {
			param = new JSONObject();
			key = _default;
		}

		// 如果没有指定渲染器的取值属性名,那么采用和该列的property,如果都没指定 那就没办法了...
		if (!param.containsKey("property")) {
			param.accumulate("property", property);
		}

		// 实例化并初始化渲染器
		renderer = (Renderer) Configuration.getRenderer(key).newInstance();
		renderer.initialize(param);
	}

	@Override
	public JSONObject to() throws Exception {
		return super.to();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	public String getWidth() {
		return width;
	}

	public void setWidth(String width) {
		this.width = width;
	}

	public Renderer getRenderer() {
		return renderer;
	}

	public void setRenderer(Renderer renderer) {
		this.renderer = renderer;
	}

}